<template>
  <div >
    <!-- 图片上传组件辅助 -->
    <el-upload
        class="avatar-uploader quill-img"
        :action="dataObj.host"
        :data="dataObj"
        name="file"
        :show-file-list="false"
        :on-success="uploadImgSuccess"
        :on-error="uploadFileError"
        :before-upload="uploadImgBefore"
        accept=".jpg, .jpeg, .png, .gif"
        multiple="multiple"
    ></el-upload>
    <!-- 视频上传组件辅助 -->
    <el-upload
        class="avatar-uploader quill-video"
        :action="dataObj.host"
        :data="dataObj"
        name="file"
        :show-file-list="false"
        :on-success="uploadVideoSuccess"
        :on-error="uploadFileError"
        :before-upload="uploadVideoBefore"
        accept=".mp4"
    ></el-upload>
    <!-- 富文本组件 -->
    <QuillEditor
        id="editorId"
        class="editor"
        ref="myQuillEditor"
        v-model:content="content"
        theme="snow"
        contentType="html"
        :options="options"
    />
  </div>
</template>
<script setup >//在这里申明使用ts进行代码的校验
import { QuillEditor, Quill } from "@vueup/vue-quill";
import { ElMessage } from "element-plus";
import "@vueup/vue-quill/dist/vue-quill.snow.css";
import {policy} from "./policy";
import {getUUID} from "@/utils";

const props = defineProps({
  modelValue: {
    type: String,
    default: ""
  },
})
const { proxy } = getCurrentInstance();
const emit = defineEmits();

const content = ref(props.modelValue);

const dataObj = ref({
  policy: "",
  signature: "",
  key: "",
  ossaccessKeyId: "",
  dir: "",
  host: "",
  // callback:'',
});
const options = ref({
  modules: {
    toolbar: {
      container: [
        ["bold", "italic", "underline", "strike"], // 加粗 斜体 下划线 删除线
        ["blockquote", "code-block"], // 引用  代码块
        [{ list: "ordered" }, { list: "bullet" }], // 有序、无序列表
        [{ indent: "-1" }, { indent: "+1" }], // 缩进
        [{ size: ["small", false, "large", "huge"] }], // 字体大小
        [{ header: [1, 2, 3, 4, 5, 6, false] }], // 标题
        [{ color: [] }, { background: [] }], // 字体颜色、字体背景颜色
        [{ align: [] }], // 对齐方式
        ["clean"], // 清除文本格式
        ["link", "image", "video"], // 链接、图片、视频  , "video"
      ],
      handlers: {
        image: function (value) {
          if (value) {
            // 调用element图片上传
            document.querySelector(".quill-img>.el-upload").click();
          } else {
            Quill.format("image", true);
          }
        },
        video: function (value) {
          if (value) {
            // 调用element图片上传
            document.querySelector(".quill-video>.el-upload").click();
          } else {
            Quill.format("video", true);
          }
        },
      },
    },
    history: {
      delay: 1000,
      maxStack: 50,
      userOnly: false
    },
  },
});
const myQuillEditor=ref(null);


function uploadImgSuccess(response){
  let fileUrl = `${dataObj.value.host}/${dataObj.value.key}`
  // 如果上传成功
  if (fileUrl) {
    // 获取富文本实例
    let quill = toRaw(myQuillEditor.value).getQuill();
    // 获取光标位置
    let length = quill.selection.savedRange.index;
    // 插入图片，res为服务器返回的图片链接地址
    quill.insertEmbed(length, "image", fileUrl);
    // 调整光标到最后
    quill.setSelection(length + 1);
    proxy.$modal.closeLoading();
  } else {
    ElMessage({
      message: "提交失败！",
      type: "error",
    });
  }
}

function uploadFileError() {
  ElMessage({
    message: "插入十八失败！",
    type: "error",
  });
}

function uploadImgBefore(file) {
  if (file.size > 5 * 1024 * 1024){
    ElMessage({
      message: "插入的图片太大了！",
      type: "error",
    });
    return false
  }
  return fileUpload(file)
}


function uploadVideoBefore(file) {
  if (file.size > 10 * 1024 * 1024){
    ElMessage({
      message: "插入的视频太大了！",
      type: "error",
    });
    return false
  }
  return fileUpload(file)
}

function uploadVideoSuccess() {
  let fileUrl = `${dataObj.value.host}/${dataObj.value.key}`
  // 如果上传成功
  if (fileUrl) {
    // 获取富文本实例
    let quill = toRaw(myQuillEditor.value).getQuill();
    // 获取光标位置
    let length = quill.selection.savedRange.index;
    // 插入图片，res为服务器返回的图片链接地址
    quill.insertEmbed(length, "video", fileUrl);
    // 调整光标到最后
    quill.setSelection(length + 1);
    proxy.$modal.closeLoading();
  } else {
    ElMessage({
      message: "提交失败！",
      type: "error",
    });
  }
}



function fileUpload(file) {
  let fileName = null;
  if(file.name.length>8){
    fileName = file.name.slice(-8)
  }else {
    fileName = file.name
  }
  return new Promise((resolve,reject) => {
    policy().then(response => {
      dataObj.value.policy = response.policy;
      dataObj.value.signature = response.signature;
      dataObj.value.ossaccessKeyId = response.accessid;
      // _self.dataObj.key = response.dir + getUUID()+'_${filename}';
      //固定链接长度
      dataObj.value.key = response.dir + getUUID()+"_"+fileName;
      dataObj.value.dir = response.dir;
      dataObj.value.host = response.host;
      proxy.$modal.loading("上传中");
      resolve(true)
    }).catch(error => {
      resolve(false)
    })
  })
}
watch(content,() => {
  emit("update:modelValue", content.value);
})


</script>

<style>
  .editor {
    white-space: pre-wrap !important;
    line-height: normal !important;
    min-height: 192px;
    background-color: #fff;
  }
  .quill-img {
    display: none;
  }
  .quill-video {
    display: none;
  }
  .ql-container{
    min-height: 300px!important;
  }
  .quill-editor.editor {
    min-height: 210px!important;
  }
  .ql-snow .ql-tooltip[data-mode="link"]::before {
    content: "请输入链接地址:";
  }
  .ql-snow .ql-tooltip.ql-editing a.ql-action::after {
    border-right: 0px;
    content: "保存";
    padding-right: 0px;
  }

  .ql-snow .ql-tooltip[data-mode="video"]::before {
    content: "请输入视频地址:";
  }

  .ql-snow .ql-picker.ql-size .ql-picker-label::before,
  .ql-snow .ql-picker.ql-size .ql-picker-item::before {
    content: "14px";
  }
  .ql-snow .ql-picker.ql-size .ql-picker-label[data-value="small"]::before,
  .ql-snow .ql-picker.ql-size .ql-picker-item[data-value="small"]::before {
    content: "10px";
  }
  .ql-snow .ql-picker.ql-size .ql-picker-label[data-value="large"]::before,
  .ql-snow .ql-picker.ql-size .ql-picker-item[data-value="large"]::before {
    content: "18px";
  }
  .ql-snow .ql-picker.ql-size .ql-picker-label[data-value="huge"]::before,
  .ql-snow .ql-picker.ql-size .ql-picker-item[data-value="huge"]::before {
    content: "32px";
  }

  .ql-snow .ql-picker.ql-header .ql-picker-label::before,
  .ql-snow .ql-picker.ql-header .ql-picker-item::before {
    content: "文本";
  }
  .ql-snow .ql-picker.ql-header .ql-picker-label[data-value="1"]::before,
  .ql-snow .ql-picker.ql-header .ql-picker-item[data-value="1"]::before {
    content: "标题1";
  }
  .ql-snow .ql-picker.ql-header .ql-picker-label[data-value="2"]::before,
  .ql-snow .ql-picker.ql-header .ql-picker-item[data-value="2"]::before {
    content: "标题2";
  }
  .ql-snow .ql-picker.ql-header .ql-picker-label[data-value="3"]::before,
  .ql-snow .ql-picker.ql-header .ql-picker-item[data-value="3"]::before {
    content: "标题3";
  }
  .ql-snow .ql-picker.ql-header .ql-picker-label[data-value="4"]::before,
  .ql-snow .ql-picker.ql-header .ql-picker-item[data-value="4"]::before {
    content: "标题4";
  }
  .ql-snow .ql-picker.ql-header .ql-picker-label[data-value="5"]::before,
  .ql-snow .ql-picker.ql-header .ql-picker-item[data-value="5"]::before {
    content: "标题5";
  }
  .ql-snow .ql-picker.ql-header .ql-picker-label[data-value="6"]::before,
  .ql-snow .ql-picker.ql-header .ql-picker-item[data-value="6"]::before {
    content: "标题6";
  }

  .ql-snow .ql-picker.ql-font .ql-picker-label::before,
  .ql-snow .ql-picker.ql-font .ql-picker-item::before {
    content: "标准字体";
  }
  .ql-snow .ql-picker.ql-font .ql-picker-label[data-value="serif"]::before,
  .ql-snow .ql-picker.ql-font .ql-picker-item[data-value="serif"]::before {
    content: "衬线字体";
  }
  .ql-snow .ql-picker.ql-font .ql-picker-label[data-value="monospace"]::before,
  .ql-snow .ql-picker.ql-font .ql-picker-item[data-value="monospace"]::before {
    content: "等宽字体";
  }
</style>